package api;

import dao.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、获取请求中的query string中的用户名和密码
        //  给请求对象设置设置字符集，保证中文用户名也可以识别
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null || password == null || username.equals("") || password.equals("")) {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("当前输入的用户名或密码为空");
            return;
        }
        UserDao userDao = new UserDao();
        User user = userDao.getUserByName(username);
        if (user == null) {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("您的用户名或者密码错误!");
            return;
        }
        if (!password.equals(user.getPassword())) {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("您的用户名或者密码错误！");
            return;
        }
        HttpSession session = req.getSession(true);
        session.setAttribute("user", user);
        resp.sendRedirect("blog_list.html");
    }
    //通过这个方法，来检查登录状态
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if (session == null) {
            //未登录
            resp.setStatus(403);
            return;
        }
        //不仅仅是看session对象本身，还需要确认user对象存在（为了实现后续的退出登录功能）
        User user = (User) session.getAttribute("user");
        if (user == null) {
            resp.setStatus(403);
            return;
        }
        resp.setStatus(200);
    }
}
